package com.sea.physical.controller;


import com.codecrane.core.power.service.DictDetailService;
import com.codecrane.core.util.ExcelUtil;
import com.codecrane.core.util.PhysicalFreightTypeEnum;
import com.codecrane.core.web.AjaxTableReturn;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sea.physical.entity.*;
import com.sea.physical.mapper.CreateDespatchFreightMapper;
import com.sea.physical.service.*;
import com.codecrane.core.web.Ajax;
import com.codecrane.core.web.AjaxReturn;
import com.sea.supply.service.ProductPriceService;
import com.sea.supply.service.SupplierService;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;

/**
 * 运费
 * @author 陈鸿飞
 */
@Controller
@RequestMapping(value = "/sea/physical/createFreight")
public class CreateDespatchFreightController {

    @Autowired
    private ProductPriceService productPriceService;
    @Autowired
    private SupplierService supplierService;
    @Autowired
    private CreateDespatchFreightService createDespatchFreightService;
    @Autowired
    private CreatePlanService createPlanService;
    @Autowired
    private CabinetService cabinetService;
    @Autowired
    private DictDetailService dictDetailService;
    @Autowired
    private CreateDespatchFreightMapper createDespatchFreightMapper;

    @RequestMapping("/updateAll")
    public String updateAll(Model model) {
        List<CreatePlan> byCnd = createPlanService.findPaymentCreatePlanNo();
        for(CreatePlan createPlan:byCnd){
            createDespatchFreightMapper.updateRealFreightTax(createPlan.getId());
        }
        return "";
    }

    /**
     * 管理主页面
     *
     * @param model
     * @return
     */
    @RequestMapping("/main")
    public String main(Model model) {
        model.addAttribute("cabinet",cabinetService.findByCnd(null));
        model.addAttribute("country", dictDetailService.findByTypeCode("base_country", null));

        return "/sea/physical/createDespatchFreight/main";
    }
    /**
     * 管理主页面
     *
     * @param model
     * @return
     */
    @RequestMapping("/freightMain")
    public String freightMain(Model model,@RequestParam("createId")Integer createId) {
        model.addAttribute("createPlan",createPlanService.findById(createId));
        model.addAttribute("supplier",supplierService.findByCnd(null));
        model.addAttribute("paymentType", dictDetailService.findByTypeCode("payment_type", null));
        return "/sea/physical/createDespatchFreight/freightMain";
    }

    @RequestMapping("/import")
    @ResponseBody
    public AjaxReturn importClubDo(Model model,@RequestParam("productMember")String productMember, MultipartFile file) {
        AjaxReturn result = Ajax.fail().setMsg("保存失败！");
        try {
            if (null == file || file.isEmpty()) {
                return result.setMsg("请上传文件！！！");
            } else {
                String fileName = file.getOriginalFilename();
                if (!(fileName.contains(".xls"))) {
                    return result.setMsg("只能上传excel文件！！！");
                }
                createDespatchFreightService.importDespatchFreight(file.getInputStream(), fileName,productMember);
                result.setOk(true);
                result.setMsg("上传成功！！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.setMsg(e.getMessage());
            return result;
        }
        return result;
    }


    /**
     * 根据创建ID获取明细
     * @param createId
     * @return
     */
    @RequestMapping("/findByCreateId")
    @ResponseBody
    public List<CreateDespatchFreight> findByCreateId(@RequestParam("createId")Integer createId){
        return createDespatchFreightService.findByCreateId(createId);
    }
    /**
     * 分页条件查询
     *
     * @param pagesize
     * @param start
     * @return
     */
    @ResponseBody
    @RequestMapping("/findByCnd")
    public AjaxTableReturn findByCnd(@RequestParam(value = "limit", defaultValue = "10") int pagesize,
                                     @RequestParam(value = "offset", defaultValue = "0") int start,
                                     CreateDespatchFreight freight) {
        start = start > 0 ? start / pagesize + 1 : 1;
        PageHelper.startPage(start, pagesize);
        List<CreateDespatchFreight> list = createDespatchFreightService.findByCnd(freight);
        PageInfo<CreateDespatchFreight> page = new PageInfo<>(list);
        return Ajax.tableDataOk(page.getTotal(), page.getList());
    }

    /**
     * 保存
     * @param freight
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public AjaxReturn usave(CreateDespatchFreight freight) {
        AjaxReturn result = Ajax.fail().setMsg("保存失败！");
        try {
            if (null != freight && createDespatchFreightService.save(freight) > 0) {
                result.setOk(true).setMsg("保存成功！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.setMsg(e.getMessage());
        }
        return result;
    }

    /**
     * 保存
     * @param id
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    public AjaxReturn delete(Integer id) {
        AjaxReturn result = Ajax.fail().setMsg("保存失败！");
        try {
            if (null != id && createDespatchFreightService.delete(id) > 0) {
                result.setOk(true).setMsg("保存成功！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.setMsg(e.getMessage());
        }
        return result;
    }

    /**
     * 导出当前数据
     * @param response
     */
    @RequestMapping(value = "/exportDetail")
    @ResponseBody
    public void exportDetail(HttpServletRequest request, HttpServletResponse response)
    {
        List<CreateDespatchFreight> list = createDespatchFreightService.findDetail();
        String[] title = {"柜号","供应商","币种","金额","状态","类型","付款方式","订舱费用"};
        String fileName = "运费报表" + org.apache.http.client.utils.DateUtils.formatDate(new Date(), "yyyyMMdd") + ".xls";
        String sheetName = "运费报表";
        String[][] content = new String[list.size()][7];
        for (int i = 0; i < list.size(); i++) {
            content[i] = new String[title.length];
            CreateDespatchFreight map = list.get(i);
            content[i][0] = map.getCreatePlanNo();
            content[i][1] = map.getCreateSupplier();
            content[i][2] = map.getCreateMoneyType();
            content[i][3] = map.getCreateMoney()+"";
            content[i][4] = map.getCreatePay()==0?"未付款":"已付款";
            content[i][5] = PhysicalFreightTypeEnum.getFreightType(map.getFlag());
        }
        //创建HSSFWorkbook 艾弗森
        HSSFWorkbook wb = ExcelUtil.getHSSFWorkbook(sheetName, title, content, null);
        //响应到客户端
        try {
            this.setResponseHeader(response, fileName);
            OutputStream os = response.getOutputStream();
            wb.write(os);
            os.flush();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 发送响应流方法
    public void setResponseHeader(HttpServletResponse response, String fileName) {
        try {
            try {
                fileName = new String(fileName.getBytes(), "ISO8859-1");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            response.setContentType("application/octet-stream;charset=ISO8859-1");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            response.addHeader("Pargam", "no-cache");
            response.addHeader("Cache-Control", "no-cache");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}
